#include "bsp_rtc.h"
#include "hal_data.h"
#include "r_rtc.h"
#include "bsp_timer.h"
#include "common_utils.h"


#define SET_YEAR  2025
#define SET_MON    10
#define SET_DAY    25
#define SET_HOUR   22
#define SET_MIN    55
#define SET_SEC     0


rtc_time_t now;

void rtc_init(void)
{
    rtc_time_t t = {0};

    t.tm_year = SET_YEAR - 1900;
    t.tm_mon  = SET_MON - 1;
    t.tm_mday = SET_DAY;
    t.tm_hour = SET_HOUR;
    t.tm_min  = SET_MIN;
    t.tm_sec  = SET_SEC;

    R_RTC_Open(&g_rtc0_ctrl, &g_rtc0_cfg);
    R_RTC_ClockSourceSet(&g_rtc0_ctrl);

    fsp_err_t err = R_RTC_CalendarTimeSet(&g_rtc0_ctrl, &t);

    if (FSP_SUCCESS != err)
        __BKPT(0);

}

void rtc_get_time(rtc_time_t *pt)
{
    fsp_err_t err = R_RTC_CalendarTimeGet(&g_rtc0_ctrl, pt);

    if (FSP_SUCCESS != err)
        __BKPT(0);
}

void rtc_task(void)
{
    static uint32_t dwrtc_tick=0;
    if(GetSysTick()-dwrtc_tick>1000)
    {
        rtc_get_time(&now);
        APP_PRINT("RTC: %04d-%02d-%02d %02d:%02d:%02d\r\n",
               now.tm_year + 1900,
               now.tm_mon + 1,
               now.tm_mday,
               now.tm_hour,
               now.tm_min,
               now.tm_sec);
        dwrtc_tick=GetSysTick();
    }
}
